package com.eyas.business.config.webmvc.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: 王龙龙
 * @Date: 2019/2/21 13:34
 * @Description:
 */
public class UrlAccessInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(UrlAccessInterceptor.class);
    private ThreadLocal<Long> startTime = new ThreadLocal<>();
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //此方法用于记录每个url的访问时间耗时
        //用于校验登录情况
        startTime.set(System.currentTimeMillis());
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        long endTime = System.currentTimeMillis();
        logger.info("URL["+request.getRequestURL().toString()+"] custom "+(endTime-startTime.get())+"ms");

    }

}
